<template>
  <div class="home" >
    <HeroBanner :slides="carouselSlides" />
    <div class="content-layout">
      <main class="home-main-content">
        <MomentsList />

        <div>
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane
              v-for="category in categories"
              :key="category.id"
              :name="String(category.id)"
            >
              <template slot="label">
                <span class="label-info">
                  <i :class="category.icon"></i>
                  {{ category.name }}
                </span>
              </template>
              <ArticleList
                :articles="articleList"
                :loading="loading"
                :total="total"
                :params="params"
                @article-click="goToPost"
                @page-change="changePage"
                class="article-list"
              />
            </el-tab-pane>
          </el-tabs>
        </div>
      </main>
      <Sidebar />
    </div>
  </div>
</template>

<script>
import ArticleList from "@/components/ArticleList/index.vue";
import HeroBanner from "@/views/home/components/HeroBanner.vue";
import Sidebar from "@/components/Sidebar/index.vue";
import MomentsList from "@/views/home/components/moments.vue";
import {
  getArticlesApi,
  getCarouselArticlesApi,
  getAllCategoriesApi,
} from "@/api/article";

export default {
  name: "Home",
  components: {
    ArticleList,
    HeroBanner,
    Sidebar,
    MomentsList,
  },
  data() {
    return {
      total: 0,
      params: {
        pageNum: 1,
        pageSize: 10,
      },
      articleList: [],
      carouselSlides: [],
      loading: false,
      activeName: "all",
      categories: [
        {
          id: "all",
          name: "全部",
          icon: "el-icon-menu",
        },
      ],
    };
  },
  methods: {
    /**
     * 切换标签
     * @param {string} tab 标签
     * @param {Event} event 事件
     */
    handleClick(tab) {
      this.params.categoryId = tab.name === "all" ? null : tab.name;
      this.params.pageNum = 1;
      this.getArticleList();
    },
    /**
     * 跳转到文章详情
     * @param {number} id 文章id
     */
    goToPost(id) {
      this.$router.push(`/post/${id}`);
    },
    /**
     * 切换页码
     * @param {number} page 页码
     */
    changePage(page) {
      this.params.pageNum = page;
      this.getArticleList();
      window.scrollTo({
        top: this.$refs.postsSection?.offsetTop - 80,
        behavior: "smooth",
      });
    },
    /**
     * 获取文章列表
     */
    getArticleList() {
      this.loading = true;
      getArticlesApi(this.params)
        .then((res) => {
          this.articleList = res.data.records;
          this.total = res.data.total;
        })
        .catch((error) => {
          console.error("Failed to fetch articles:", error);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /**
     * 获取轮播和推荐文章
     */
    getCarouselArticles() {
      getCarouselArticlesApi().then((res) => {
        this.carouselSlides = res.data;
      });
    },
    /**
     * 获取所有分类
     */
    getAllCategories() {
      getAllCategoriesApi().then((res) => {
        const icons = [
          "el-icon-document",
          "el-icon-collection",
          "el-icon-reading",
          "el-icon-coffee-cup",
          "el-icon-notebook-2",
          "el-icon-edit",
        ];
        
        // 排序：sort 数值越大越在前，null 排在最后
        const sortedCategories = res.data.sort((a, b) => {
          // 如果两个都是 null，保持原顺序
          if (a.sort === null && b.sort === null) return 0;
          // 如果 a 是 null，a 排在后面
          if (a.sort === null) return 1;
          // 如果 b 是 null，b 排在后面
          if (b.sort === null) return -1;
          // 都有值，按降序排列（数值大的在前）
          return b.sort - a.sort;
        });
        
        const categoriesWithIcons = sortedCategories.map((category) => ({
          ...category,
          icon: icons[Math.floor(Math.random() * icons.length)],
        }));
        this.categories.push(...categoriesWithIcons);
      });
    },
  },
  created() {
    this.getArticleList();
    this.getCarouselArticles();
    this.getAllCategories();
  },
};
</script>

<style lang="scss" scoped>
.home {
  width: 100%;
  margin: 0;
  padding: 0;
  margin-top: -70px; /* 负margin抵消可能存在的padding */
  animation: fadeIn 0.6s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.content-layout {
  display: grid;
  grid-template-columns: minmax(0, 1fr) 320px;
  gap: $spacing-xl * 2;
  max-width: 1400px;
  margin: 0 auto;
  padding: $spacing-xl * 2 $spacing-xl;
  align-items: start;

  @include responsive(lg) {
    grid-template-columns: 1fr;
    padding: $spacing-lg;
    gap: $spacing-xl;
  }
  
  @include responsive(md) {
    padding: $spacing-md;
  }
}

.home-main-content {
  min-width: 0;
  width: 100%;
  height: 100%;
}

// 优化 Tabs 样式
:deep(.el-tabs) {
  .el-tabs__header {
    margin-bottom: $spacing-xl;
    border-bottom: 2px solid rgba(99, 102, 241, 0.1);
    
    :root[data-theme='dark'] & {
      border-bottom-color: rgba(99, 102, 241, 0.15);
  }
}

  .el-tabs__nav-scroll {
  overflow-x: scroll !important;
    padding-bottom: 8px;

  &::-webkit-scrollbar {
    display: none !important;
  }
}
  
  .el-tabs__nav-wrap::after {
  display: none;
}
  
  .el-tabs__active-bar {
    background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
    height: 3px;
    border-radius: 3px;
  }
  
  .el-tabs__item {
    font-size: 15px;
    font-weight: 500;
    color: var(--text-secondary);
    padding: 0 $spacing-lg;
    height: 46px;
    line-height: 46px;
    transition: all 0.3s ease;
    
    &:hover {
      color: #667eea;
      transform: translateY(-2px);
    }
    
    &.is-active {
      color: #667eea;
      font-weight: 600;
    }
  }
}

.label-info {
  display: flex;
  align-items: center;
  gap: $spacing-sm;
  color: var(--text-primary);
  transition: all 0.3s ease;
  
  i {
    font-size: 1.1em;
    transition: transform 0.3s ease;
  }
  
  &:hover i {
    transform: scale(1.2) rotate(10deg);
  }
}
</style>
